const express = require('express');
const router = express.Router();
//导入数据库操作模块
const db = require('../db/index');
const multer = require('multer')

// 配置上传文件目录和文件名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../uploads/');
    },
    filename: function (req, file, cb) {
        //将Date.now格式化成YYYYMMDDHHmmss时间格式
        const date = new Date();
        const year = date.getFullYear().toString();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        const formattedDate = `${year}${month}${day}${hours}${minutes}${seconds}`;

        let filename = formattedDate + '-' + file.originalname;
        cb(null, filename);
    }
});

// 创建multer实例
const upload = multer({ storage: storage });

//上传图片接口
router.post('/upload', (req, res) => {
    // single表示只上传一张图片，upload.single('file')中的'file'对应前端上传控件的name属性
    upload.single('file')(req, res, function (err) {
        if (err) {
            console.log(err);
            return res.status(500).json({ message: 'Failuread' });
        }
        return res.send({
            code: 200,
            message: 'Success',
            url: '/pic/' + req.file.filename
        })
    });
})


//创建商品
router.post('/create', (req, res) => {
    const { title, descrption, price, pic, count, category_id } = req.body;

    if (!title || !descrption || !price || !pic || !count || !category_id) {
        return res.send({ code: 400, message: 'Missing required fields' });
    }

    const newProduct = {
        title,
        descrption,
        price,
        pic,
        status: 1,
        count,
        category_id
    };

    db.query('INSERT INTO goods SET ?', newProduct, (err, result) => {
        if (err) {
            console.log(err);
            return res.send({ code: 500, message: '服务器错误[1]' });
        }

        return res.status(200).json({ code: 200, message: '创建成功' });
    });
});

//批量删除商品
router.delete('/del', (req, res) => {
    const ids = req.body.ids;

    db.query(`DELETE FROM goods WHERE id IN (${ids.toString()})`, (err, result) => {
        if (err) {
            res.status(500).json({ code: 500, message: '服务器出错' });
        } else if (result.affectedRows === 0) {
            res.status(400).json({ code: 400, message: '该商品不存在' });
        } else {
            res.status(200).json({ code: 200, message: '删除成功' });
        }
    });
});


//获取所有商品 分页
router.get('/all', (req, res) => {
    const { start, limit } = req.query;

    db.query(`SELECT * FROM goods LIMIT ${+start},${+limit}`, (err, goods) => {
        if (err) {
            return res.send({ code: 500, message: '服务器出错[1]' });
        }

        db.query('SELECT COUNT(*) AS count FROM goods', (err, result) => {
            if (err) {
                return res.send({ code: 500, message: '服务器出错[2]' });
            }

            return res.send({
                code: 200,
                message: '获取成功',
                total: result[0].count,
                goods,
            });
        });
    });
});

//编辑商品信息
router.post('/edit', (req, res) => {
    const { id, title, descrption, price, pic, count, category_id } = req.body;

    db.query(
        `UPDATE goods SET title='${title}', descrption='${descrption}', price=${price}, pic='${pic}', count=${count}, category_id=${category_id} WHERE id='${id}'`,
        (err, result) => {
            if (err) {
                res.status(500).json({ code: 500, message: err });
            } else if (result.affectedRows === 0) {
                res.status(400).json({ code: 400, message: '该商品不存在' });
            } else {
                res.status(200).json({ code: 200, message: '编辑成功' });
            }
        }
    );
});

//商品上下架
router.post('/status', (req, res) => {
    const { id, status } = req.body

    const sql = `UPDATE goods SET status='${status}' where id=${id}`

    db.query(sql, [id, status], (err, result) => {
        if (err) {
            console.log(err);
            res.status(500).json({ code: 500, message: '服务器出错' });
        } else if (result.affectedRows === 0) {
            res.status(400).json({ code: 400, message: '操作失败' });
        } else {
            res.status(200).json({ code: 200, message: '操作成功' });
        }
    })
})


module.exports = router;